package org.akomantoso.core.io.util;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.akomantoso.core.data.CollectionBodyElement;
import org.akomantoso.core.data.ComponentRef;
import org.akomantoso.core.data.Interstitial;
import org.akomantoso.core.io.Input;
import org.akomantoso.core.io.InputConstants;
import org.akomantoso.core.io.util.group.DocumentTypeGroup;
import org.akomantoso.core.util.MapUtil;

/**
 * @author <a href="mailto:jacques.militello@gmail.com">Jacques Militello</a>
 */
public final class CollectionBodyElementUtil {

	private CollectionBodyElementUtil() {
	}

	static final Map<String, Instantiator<CollectionBodyElement>> MAP;

	public static void read(Input in, List<CollectionBodyElement> elements) throws IOException {

		CollectionBodyElement contentElement = null;
		final String localName = in.getLocalName();

		int eventType;
		
		while (true) {
			eventType = in.readNext();
			switch (eventType) {
			case InputConstants.START_ELEMENT:
				elements.add(contentElement = instantiate(in.getLocalName()));
				contentElement.readExternal(in);
				break;
			case InputConstants.END_ELEMENT:
				if (localName.equals(in.getLocalName())) {
					return;
				}
			}
		}
	}

	private static CollectionBodyElement instantiate(String elementName) {
		final Instantiator<? extends CollectionBodyElement> instatiator = MAP.get(elementName);
		if (instatiator == null) {
			throw new RuntimeException("Tag [" + elementName + "] not supported for CollectionContentElement ?!?");
		}
		return instatiator.instantiate();
	}

	static {

		Map<String, Instantiator<CollectionBodyElement>> temp = new HashMap<String, Instantiator<CollectionBodyElement>>();

		MapUtil.copy(DocumentTypeGroup.MAP, temp);

		// interstitial
		temp.put(Interstitial.ELEMENT, new Instantiator<CollectionBodyElement>() {
			public Interstitial instantiate() {
				return new Interstitial();
			}
		});

		// componentRef
		temp.put(ComponentRef.ELEMENT, new Instantiator<CollectionBodyElement>() {
			public ComponentRef instantiate() {
				return new ComponentRef();
			}
		});

		MAP = Collections.unmodifiableMap(temp);
	}

}
